package com.taorenqi.business.fragment.mine;


import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.taorenqi.business.R;
import com.taorenqi.business.app.MyApp;
import com.taorenqi.business.event.PersonalEvent;
import com.taorenqi.business.event.RechargeEvent;
import com.taorenqi.business.fragment.base.BaseBackFragment;
import com.taorenqi.business.helper.payment.AliPayUtils;
import com.taorenqi.business.utils.Encoder;
import com.taorenqi.business.utils.StringUtils;
import com.taorenqi.business.utils.ToastUtil;
import com.taorenqi.business.widget.menu.MenuLinearLayout;
import com.taorenqi.business.widget.menu.MenuLinearLayoutFinal;
import com.taorenqi.business.widget.statusview.StatusView;
import com.taorenqi.business.widget.subscribers.PageDataSubscriberOnNext;
import com.taorenqi.business.widget.subscribers.ProgressSubscriber;
import com.taorenqi.data.common.BasePageableResponse;
import com.taorenqi.data.entity.payment.AliPayResponseEntity;
import com.taorenqi.data.service.PaymentDataHttpRequest;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static java.lang.Integer.parseInt;

/**
 * 充值
 * A simple {@link Fragment} subclass.
 */
public class RechargeFragment extends BaseBackFragment implements RadioGroup.OnCheckedChangeListener{


    @Bind(R.id.status_view)
    StatusView statusView;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.et_buy_gb_num)
    EditText etBuyGbNum;
    @Bind(R.id.rb_buy_gb_1)
    RadioButton rbBuyGb1;
    @Bind(R.id.rb_buy_gb_2)
    RadioButton rbBuyGb2;
    @Bind(R.id.rb_buy_gb_3)
    RadioButton rbBuyGb3;
    @Bind(R.id.gb_buy_gb)
    RadioGroup gbBuyGb;
    @Bind(R.id.menull_pri_1)
    MenuLinearLayout menullPri1;
    @Bind(R.id.menull_pri_2)
    MenuLinearLayout menullPri2;
    @Bind(R.id.menull_pri_3)
    MenuLinearLayout menullPri3;
    @Bind(R.id.ll_buy_gb_1)
    LinearLayout llBuyGb1;
    @Bind(R.id.hs_buy_gb_1)
    HorizontalScrollView hsBuyGb1;
    @Bind(R.id.menull_hot_1)
    MenuLinearLayout menullHot1;
    @Bind(R.id.menull_hot_2)
    MenuLinearLayout menullHot2;
    @Bind(R.id.hs_buy_gb_2)
    HorizontalScrollView hsBuyGb2;
    @Bind(R.id.menull_fin_1)
    MenuLinearLayoutFinal menullFin1;
    @Bind(R.id.hs_buy_gb_3)
    HorizontalScrollView hsBuyGb3;
    @Bind(R.id.iv_buy_vip_pay_icon)
    ImageView ivBuyVipPayIcon;
    @Bind(R.id.iv_buy_vip_pay_name)
    TextView ivBuyVipPayName;
    @Bind(R.id.ll_buy_gb_pay)
    LinearLayout llBuyGbPay;
    @Bind(R.id.tv_buy_vip_now_price)
    TextView tvBuyVipNowPrice;
    @Bind(R.id.tv_buy_vip_commit)
    TextView tvBuyVipCommit;
    @Bind(R.id.recharge_container)
    LinearLayout rechargeContainer;

    private RadioButton rbAlipay;
    private RadioButton rbWechatpay;
    private RadioButton rbYibaopay;
    private RadioGroup  rgPay;
    private Dialog      dialog_pay;

    private int pay = 0;
    private BasePageableResponse<AliPayResponseEntity> data;
    private PageDataSubscriberOnNext<BasePageableResponse<AliPayResponseEntity>> aliPaySubscriber;

    public static RechargeFragment newInstance() {
        // Required empty public constructor
        RechargeFragment fragment = new RechargeFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_recharge, container, false);
        ButterKnife.bind(this, view);
        initToolbar();
        initGroup();
        initPay(pay);
        initHttpRequestData();
        initPri();//初始化最初套餐
        initHot();//初始化火爆套餐
        initFin();//初始化终极套餐
        initEdit();
        return attachToSwipeBack(view);
    }

    private void initToolbar() {
        toolbar.setTitle("充值G币");
        initToolbarNav(toolbar);
    }

    private void initHttpRequestData() {

        aliPaySubscriber = new PageDataSubscriberOnNext<BasePageableResponse<AliPayResponseEntity>>() {
            @Override
            public void onNext(BasePageableResponse<AliPayResponseEntity> entity) {
                //接口请求成功后处理,调起支付。
                data = entity;
                AliPayUtils.getInstant(_mActivity).pay(entity);
            }
        };
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private void initEdit() {
        etBuyGbNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() >= 3) {
                    int i = parseInt(editable.toString());
                    if (i < 100 && i >= 0) {
                        tvBuyVipNowPrice.setText( "0");
                    } else {
                        tvBuyVipNowPrice.setText(i + "");
                    }
                }else {
                    tvBuyVipNowPrice.setText( "0");
                }
            }
        });
    }
    /**
     * 初始化radiogroup
     */
    private void initGroup() {
        gbBuyGb.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                if (checkedId == rbBuyGb1.getId()) {
                    rbBuyGb1.setBackgroundResource(R.drawable.buy_gb_rb_first_sel);
                    rbBuyGb1.setTextColor(getResources().getColor(R.color.white));

                    rbBuyGb2.setBackgroundColor(getResources().getColor(R.color.comparaGray));
                    rbBuyGb2.setTextColor(getResources().getColor(R.color.comparaText));

                    rbBuyGb3.setBackgroundResource(R.drawable.buy_gb_rb_third_unsel);
                    rbBuyGb3.setTextColor(getResources().getColor(R.color.comparaText));

                    hsBuyGb1.setVisibility(View.VISIBLE);
                    hsBuyGb2.setVisibility(View.GONE);
                    hsBuyGb3.setVisibility(View.GONE);

                }
                if (checkedId == rbBuyGb2.getId()) {
                    rbBuyGb1.setBackgroundResource(R.drawable.buy_gb_rb_first_unsel);
                    rbBuyGb1.setTextColor(getResources().getColor(R.color.comparaText));

                    rbBuyGb2.setBackgroundColor(getResources().getColor(R.color.login_orange));
                    rbBuyGb2.setTextColor(getResources().getColor(R.color.white));

                    rbBuyGb3.setBackgroundResource(R.drawable.buy_gb_rb_third_unsel);
                    rbBuyGb3.setTextColor(getResources().getColor(R.color.comparaText));

                    hsBuyGb1.setVisibility(View.GONE);
                    hsBuyGb2.setVisibility(View.VISIBLE);
                    hsBuyGb3.setVisibility(View.GONE);


                }
                if (checkedId == rbBuyGb3.getId()) {
                    rbBuyGb1.setBackgroundResource(R.drawable.buy_gb_rb_first_unsel);
                    rbBuyGb1.setTextColor(getResources().getColor(R.color.comparaText));

                    rbBuyGb2.setBackgroundColor(getResources().getColor(R.color.comparaGray));
                    rbBuyGb2.setTextColor(getResources().getColor(R.color.comparaText));

                    rbBuyGb3.setBackgroundResource(R.drawable.buy_gb_rb_third_sel);
                    rbBuyGb3.setTextColor(getResources().getColor(R.color.white));

                    hsBuyGb1.setVisibility(View.GONE);
                    hsBuyGb2.setVisibility(View.GONE);
                    hsBuyGb3.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @OnClick({R.id.rb_buy_gb_1, R.id.rb_buy_gb_2, R.id.rb_buy_gb_3, R.id.ll_buy_gb_pay,
            R.id.tv_buy_vip_commit,R.id.menull_hot_1, R.id.menull_hot_2, R.id.menull_pri_1,
            R.id.menull_pri_2, R.id.menull_pri_3, R.id.menull_fin_1})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rb_buy_gb_1:
                initPri();
                break;
            case R.id.rb_buy_gb_2:
                initHot();
                break;
            case R.id.rb_buy_gb_3:
                initFin();
                break;
            case R.id.menull_hot_1://火爆套餐_1
                menullHot1.setClick(true);
                menullHot2.setClick(false);
                hotMenuIsClick(menullHot1);
                hotMenuIsClick(menullHot2);
                tvBuyVipNowPrice.setText("20000");
                etBuyGbNum.setText("20000");
                break;
            case R.id.menull_hot_2://火爆套餐_2
                menullHot1.setClick(false);
                menullHot2.setClick(true);
                hotMenuIsClick(menullHot1);
                hotMenuIsClick(menullHot2);
                tvBuyVipNowPrice.setText("30000");
                etBuyGbNum.setText("30000");
                break;
            case R.id.menull_pri_1://初级套餐1
                menullPri1.setClick(true);
                menullPri2.setClick(false);
                menullPri3.setClick(false);

                priMenuIsClick(menullPri1);
                priMenuIsClick(menullPri2);
                priMenuIsClick(menullPri3);
                tvBuyVipNowPrice.setText("2000");
                etBuyGbNum.setText("2000");
                break;
            case R.id.menull_pri_2://初级套餐2
                menullPri1.setClick(false);
                menullPri2.setClick(true);
                menullPri3.setClick(false);

                priMenuIsClick(menullPri1);
                priMenuIsClick(menullPri2);
                priMenuIsClick(menullPri3);
                tvBuyVipNowPrice.setText("5000");
                etBuyGbNum.setText("5000");
                break;
            case R.id.menull_pri_3://初级套餐3
                menullPri1.setClick(false);
                menullPri2.setClick(false);
                menullPri3.setClick(true);

                priMenuIsClick(menullPri1);
                priMenuIsClick(menullPri2);
                priMenuIsClick(menullPri3);
                tvBuyVipNowPrice.setText("10000");
                etBuyGbNum.setText("10000");
                break;
            case R.id.menull_fin_1://终极套餐
                if (menullFin1.isClick()) {//非选中状态
                    menullFin1.setClick(false);
                    finMenuIsClick(menullFin1);
                    tvBuyVipNowPrice.setText("0");
                    etBuyGbNum.setText("0");
                } else {//选中状态
                    menullFin1.setClick(true);
                    finMenuIsClick(menullFin1);
                    tvBuyVipNowPrice.setText("50000");
                    etBuyGbNum.setText("50000");
                }
                break;
            case R.id.ll_buy_gb_pay://支付
                showdialog_pay();
                break;
            case R.id.tv_buy_vip_commit://确认支付

                int price =Integer.parseInt(tvBuyVipNowPrice.getText().toString().trim());

                switch (pay) {
                    case 0:
                        Toast.makeText(_mActivity, "选择支付方式", Toast.LENGTH_SHORT).show();
                        return;
                    case 1:
                        if (price < 100 || price % 100 !=0){
                            ToastUtil.showToast(_mActivity,"请输入大于100且是100的整数倍的金额");
                        }else {
                            initAlipay();
                        }
                        break;
                    case 2:
                        ToastUtil.showToast(_mActivity,"微信支付开发中，请选择支付宝支付");
                        break;
                    case 3:
                        ToastUtil.showToast(_mActivity,"易宝支付开发中，请选择支付宝支付");
                        break;
                }

                break;


        }
    }

    private void initAlipay() {
        String money = tvBuyVipNowPrice.getText().toString().trim();
        int type = pay;
        HashMap map = new HashMap();
        map.put("shop_rechage_money", money);
        map.put("shop_bank", type + "");
        String sign = Encoder.getSigns(map);
        PaymentDataHttpRequest.getInstance(MyApp.getApp()).requestAliPayForGb(new ProgressSubscriber(aliPaySubscriber, _mActivity),money,type,sign);
    }

    private void showdialog_pay() {

        dialog_pay = new Dialog(_mActivity, R.style.my_dialog);
        dialog_pay.setCanceledOnTouchOutside(true);
        LinearLayout view = (LinearLayout) LayoutInflater.from(_mActivity).inflate(R.layout.compara_pay, null);
        rgPay = (RadioGroup) view.findViewById(R.id.rg_pay);
        rbAlipay = (RadioButton) view.findViewById(R.id.rb_alipay);
        rbWechatpay = (RadioButton) view.findViewById(R.id.rb_wechatpay);
        rbYibaopay = (RadioButton) view.findViewById(R.id.rb_yibaopay);


        rgPay.setOnCheckedChangeListener(this);

        dialog_pay.setContentView(view);
        Window dialogWindow = dialog_pay.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
//        dialogWindow.setWindowAnimations(R.style.dialogstyle);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        lp.x = 0; // 新位置X坐标
        lp.y = -20; // 新位置Y坐标
        //lp.y = getWindowManager().getDefaultDisplay().getHeight();; // 新位置Y坐标
        //lp.width = (int) getResources().getDisplayMetrics().widthPixels; // 宽度
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT; // 宽度
        view.measure(0, 0);
        //lp.height = view.getMeasuredHeight();
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        lp.alpha = 9f; // 透明度
        //dialogWindow.setAttributes(lp);
        dialogWindow.setAttributes(lp);
        dialog_pay.show();
    }

    private void initPri() {

        menullPri1.setPrice("¥2000套餐");
        menullPri1.setDiscount("充值折扣9.1折");
        menullPri1.setGbNum("2200G币");

        menullPri2.setPrice("¥5000套餐");
        menullPri2.setDiscount("充值折扣8.9折");
        menullPri2.setGbNum("5600G币");

        menullPri3.setPrice("¥10000套餐");
        menullPri3.setDiscount("充值折扣8.7折");
        menullPri3.setGbNum("11400G币");

        if (hsBuyGb1.getVisibility() == View.VISIBLE) {
            menullPri1.setClick(false);
            menullPri2.setClick(false);
            menullPri3.setClick(false);

            priMenuIsClick(menullPri1);
            priMenuIsClick(menullPri2);
            priMenuIsClick(menullPri3);

        } else {
            menullPri1.setClick(false);
            menullPri2.setClick(false);
            menullPri3.setClick(false);

            priMenuIsClick(menullPri1);
            priMenuIsClick(menullPri2);
            priMenuIsClick(menullPri3);
        }

    }

    /**
     * 初始套餐的点击效果变化
     *
     * @param menuLinearLayout
     */
    private void priMenuIsClick(MenuLinearLayout menuLinearLayout) {
        if (menuLinearLayout.isClick()) {//点击了的效果
            menuLinearLayout.setClickColor(
                    R.drawable.buy_gb_pri_sel,
                    getResources().getColor(R.color.white),
                    getResources().getColor(R.color.white),
                    getResources().getColor(R.color.white),
                    getResources().getColor(R.color.white),
                    getResources().getColor(R.color.white)
            );

        } else {//非点击效果
            menuLinearLayout.setNormalColor(
                    R.drawable.buy_gb_pri_unsel,
                    getResources().getColor(R.color.buy_gb_pri_green),
                    getResources().getColor(R.color.myGrayText),
                    getResources().getColor(R.color.myGrayText),
                    getResources().getColor(R.color.myGrayText),
                    getResources().getColor(R.color.login_orange));
        }
    }


    /**
     * 初始化火爆套餐
     */
    private void initHot() {


        //menullHot1.setLabel("强烈推荐");
        menullHot1.setPrice("¥20000套餐");
        menullHot1.setDiscount("充值折扣8.6折");
        menullHot1.setGbNum("23000G币");

        // menullHot2.setLabel("强烈推荐");
        menullHot2.setPrice("¥30000套餐");
        menullHot2.setDiscount("充值折扣8.5折");
        menullHot2.setGbNum("35000G币");

        /**
         * 设置整体的常规颜色
         * @param body 主体的背景颜色
         * @param price 价钱的颜色
         * @param line 中间那条线的颜色
         * @param discount 折扣的颜色
         * @param huode "获得"颜色的
         * @param gbnum GB的数量的颜色
         * @param labelBackcolor 右上角标签的颜色 背景
         * @param labelTextcolor 右上角标签的颜色 字体颜色
         *
         */


        if (hsBuyGb2.getVisibility() == View.VISIBLE) {
            menullHot1.setClick(false);
            menullHot2.setClick(false);
            hotMenuIsClick(menullHot1);
            hotMenuIsClick(menullHot2);

        } else {
            menullHot1.setClick(false);
            menullHot2.setClick(false);

            hotMenuIsClick(menullHot1);
            hotMenuIsClick(menullHot2);

        }
    }

    private void initFin() {
        if (hsBuyGb3.getVisibility() == View.VISIBLE) {
            menullFin1.setClick(false);
            finMenuIsClick(menullFin1);
        } else {

        }
    }

    private void hotMenuIsClick(MenuLinearLayout menuLinearLayout) {
        if (menuLinearLayout.isClick()) {//点击了的效果
            menuLinearLayout.setClickColor(
                    R.drawable.buy_gb_hot_sel,
                    getResources().getColor(R.color.white),
                    getResources().getColor(R.color.white),
                    getResources().getColor(R.color.white),
                    getResources().getColor(R.color.white),
                    getResources().getColor(R.color.white)
            );

        } else {//非点击效果
            menuLinearLayout.setNormalColor(
                    R.drawable.buy_gb_hot_unsel,
                    getResources().getColor(R.color.login_orange),
                    getResources().getColor(R.color.myGrayText),
                    getResources().getColor(R.color.myGrayText),
                    getResources().getColor(R.color.myGrayText),
                    getResources().getColor(R.color.login_orange));
        }
    }

    private void finMenuIsClick(MenuLinearLayoutFinal menuLinearLayout) {
        if (menuLinearLayout.isClick()) {//点击了的效果
            menuLinearLayout.setClickColor(
                    R.drawable.buy_gb_fin_sel,
                    getResources().getColor(R.color.white),
                    getResources().getColor(R.color.white),
                    getResources().getColor(R.color.white),
                    getResources().getColor(R.color.white),
                    getResources().getColor(R.color.white)
            );

        } else {//非点击效果
            menuLinearLayout.setNormalColor(
                    R.drawable.buy_gb_fin_unsel,
                    getResources().getColor(R.color.buy_gb_fin_purple),
                    getResources().getColor(R.color.myGrayText),
                    getResources().getColor(R.color.myGrayText),
                    getResources().getColor(R.color.myGrayText),
                    getResources().getColor(R.color.login_orange));
        }

    }

    Handler handler = new Handler();

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        if (checkedId == rbAlipay.getId()) {//支付宝支付
            pay = 1;
            initPay(pay);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    dialog_pay.dismiss();
                }
            }, 300);

        }
        if (checkedId == rbWechatpay.getId()) {//微信支付
            pay = 2;
            initPay(pay);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    dialog_pay.dismiss();
                }
            }, 300);
        }
        if (checkedId == rbYibaopay.getId()) {//易宝支付
            pay = 3;
            initPay(pay);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    dialog_pay.dismiss();
                }
            }, 300);
        }
    }

    private void initPay(int pay) {
        ivBuyVipPayIcon.setVisibility(View.VISIBLE);
        ivBuyVipPayName.setVisibility(View.VISIBLE);
        switch (pay) {
            case 0:
                ivBuyVipPayIcon.setVisibility(View.INVISIBLE);
                ivBuyVipPayName.setVisibility(View.INVISIBLE);
                break;
            case 1:
                ivBuyVipPayIcon.setImageResource(R.mipmap.zhifubao_icon);
                ivBuyVipPayName.setText("支付宝");
                break;
            case 2:
                ivBuyVipPayIcon.setImageResource(R.mipmap.weixingzhifu_icon);
                ivBuyVipPayName.setText("微信支付");
                break;
            case 3:
                ivBuyVipPayIcon.setImageResource(R.mipmap.yibaozhifu_icon);
                ivBuyVipPayName.setText("易宝支付");
                break;
        }

    }
}
